package com.bilibili.juc.arthas;

public class FindNumberStartEndIndex {
    public static void main(String[] args) {
        int[] nums = {3,4,7,7,7,7,7,8,8,9,10};
        //            0 1 2 3 4 5 6 7 8 9 10
//        int[] nums = {3,7,7,7,7,8,8,9};

        int target = 7;
        int leftIndex = getLeftIndex(nums,target);
        System.out.println(leftIndex);
        int rightIndex = getRightIndex(nums,target);
        System.out.println(rightIndex);
    }
    /**
     * 使用二分查询方法
     * @param nums
     * @param target
     * @return
     */
    private static int getLeftIndex(int[] nums,int target) {
        int start = 0;
        int end = nums.length-1;
        int rs = -1;
//        int[] nums = {3,4,7,7,7,7,7,8,8,9,10};
        while (start <= end){
            int middle = (start+end)/2;
            if (target > nums[middle]){
                start = middle+1;
            } else if (target < nums[middle]) {
                end = middle-1;
            }else {
                rs = middle;
                end = middle-1;
            }
        }
        return rs;
    }


    private static int getRightIndex(int[] nums,int target) {
        int start = 0;
        int end = nums.length-1;
        int rs = -1;
        while (start <= end){
            int middle = (start+end)/2;
            if (target > nums[middle]){
                start = middle+1;
            } else if (target < nums[middle]) {
                end = middle-1;
            }else {
                rs = middle;
                start = middle+1;
            }
        }
        return rs;
    }
}
